#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;

#define NUM 0

int g_cnt = NUM;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;

void *Count(void * args)
{
    pthread_detach(pthread_self());
    uint64_t number = (uint64_t)args;
    while(true) {
        // 并发访问全局变量cnt会导致数据不一致问题
        // 所以要对下列代码加锁
        pthread_mutex_lock(&g_mutex);
        // 这里保证了互斥，但可能会出现线程饥饿问题
        // 所以需要使用条件变量来让线程等待条件就绪
        pthread_cond_wait(&g_cond, &g_mutex);
        cout << "pthread: " << number << " , ticket =  " << g_cnt << endl;
        ++g_cnt;
        pthread_mutex_unlock(&g_mutex);
    }
    return nullptr;
}

int main()
{
    for(uint64_t i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Count, (void*)i);
    }
    cout << "main thread started" << endl;
    while(1) {
        cout << "start a thread" << endl;
        pthread_cond_signal(&g_cond);
        sleep(1);
    }
    return 0;
}